<template>
  <div class="page-albumList">
    <a-button type="primary" class="mb-[16px]" @click="multipleBackup()">批量备份</a-button>
    <a-table
      id="albumTable"
      :row-selection="{ selectedRowKeys: statusState.selectedRowKeys, checkStrictly: false, onChange: onSelectChange }"
      :expandRowByClick="false"
      row-key="table_name"
      :columns="columns"
      :pagination="false"
      :data-source="state.recycleList"
      :loading="state.loading"
      :scroll="{ x: 1500 }"
    >
      <template #bodyCell="{ column, record, index }">
        <template v-if="column.key === 'sort'">
          <menu-outlined />
        </template>
        <template v-if="column.key === 'table_name'">
          <a-tooltip placement="top" color="#fff">
            <template #title>
              {{ record.table_name }}
            </template>
            <div class="ellipsis-text">{{ record.table_name }}</div>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'table_comment'">
          <a-tooltip placement="top" color="#fff">
            <template #title>
              {{ record.table_comment }}
            </template>
            <div class="ellipsis-text">{{ record.table_comment }}</div>
          </a-tooltip>
        </template>
        <template v-else-if="column.key === 'table_rows'">
          <span>
            {{ formatNumber(record.table_rows) }}
          </span>
        </template>
        <template v-else-if="column.key === 'back_time'">
          <span v-if="record.back_time && record.back_time != '0'">
            {{ formatToDateTime(record.back_time * 1000) }}
          </span>
          <span v-else>-</span>
        </template>
        <template v-else-if="column.key === 'status'">
          <span slot="reference" v-if="record.status == 1" class="flex items-center">
            <i class="dotClass mr-[8px]" style="background-color: #03b861"></i><span>已备份</span>
          </span>
          <span slot="reference" v-if="record.status == 2" class="flex items-center">
            <i class="dotClass mr-[8px]" style="background-color: #bfbfbf"></i><span>未备份</span>
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a class="basicColor" @click="singleBackup(record, index)">备份</a>
          </span>
        </template>
      </template>
    </a-table>
    <a-pagination
      @change="handlePaginationChange"
      show-size-changer
      :defaultPageSize="10"
      :pageSizeOptions="['10', '20', '50', '100']"
      :show-total="(total:number)=>`共${total}条`"
      :total="queryState.total"
    />
    <!-- 数据操作对话框 -->
    <modal-view
      title="提示"
      v-model:visible="backupVisible"
      okText="开始备份"
      cancelText="取消"
      :width="618"
      :footer="null"
      :afterClose="afterCloseFunc"
      @cancel="backupCancel"
    >
      <a-form ref="formRef" :model="formState" :rules="formRules">
        <a-form-item label="备份名称" name="backups_name">
          <a-input
            v-model:value.trim="formState.backups_name"
            :maxlength="30"
            class="w-[466px]"
            placeholder="请输入备份的名称"
          />
          <div class="text-[12px] text-[#bfbfbf] mt-[8px]">由于备注原因或版本信息等，便于数据恢复时选择备份。</div>
        </a-form-item>
        <div class="text-[14px] text-[#595959] mt-[32px] ml-[80px]">本次备份共选择{{ backupCount }}张表</div>
      </a-form>
      <div class="mt-[32px] flex justify-end">
        <a-button type="primary" @click="backupConfirm" class="mr-[16px]" v-if="formState.backups_name"
          >开始备份</a-button
        >
        <a-button type="primary" class="mr-[16px] bg-[rgba(138,192,253)] border-0" v-else>开始备份</a-button>
        <a-button @click="backupCancel">取消</a-button>
      </div>
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { formatNumber, formatToDateTime } from '@/utils/format'
import { tableColumn } from './dataSource'
import type { BackupsItem } from '@/types/backups/backups'
import { statusState } from './state'
import ModalView from '@/components/components/modal/ModalView.vue'
import apis from '@/apis'
import { recycle_create } from '@/apis/modules/backups'
const {
  backups: { table_list }
} = apis
type Key = string
const formRef = ref()
const currentIndex = ref()
const columns = ref(tableColumn)
const backupVisible = ref(false)
const isSingleBackup = ref(false)
const backupCount = ref(0)
const state = reactive<{ loading: boolean; recycleList: BackupsItem[] }>({
  loading: false,
  recycleList: [] as BackupsItem[]
})
const formState = reactive<{ tables_name: string[] | undefined; backups_name: string | undefined }>({
  tables_name: undefined,
  backups_name: ''
})
const formRules = reactive({
  backups_name: [{ required: true, message: '请输入备份名称' }]
})

const queryState = reactive({
  offset: 0, // 默认当前页数
  limit: 10, // 默认当前页显示数据的大小
  total: 0 // 总数，必须先有
})
/**
 * 分页改变事件
 */
const handlePaginationChange = (size: number, limit: number) => {
  queryState.limit = limit
  queryState.offset = (size - 1) * limit
  getBackupList()
}
//获取数据备份接口
const getBackupList = () => {
  state.loading = true
  table_list(queryState)
    .then((res: any) => {
      res?.list.forEach((item: BackupsItem) => {
        item.status = 2
      })
      state.recycleList = res?.list
      queryState.total = res?.total
      state.loading = false
      console.log('数据恢复列表: ', state.recycleList)
    })
    .catch(() => {
      state.loading = false
    })
}
const onSelectChange = (rowKeys: Key[]) => {
  console.log('selectedRowKeys changed: ', rowKeys)
  statusState.selectedRowKeys = rowKeys
}
//批量备份
const multipleBackup = () => {
  const len = statusState.selectedRowKeys.length
  if (len <= 0) return message.warning('请选择至少一条数据进行备份')
  formState.tables_name = statusState.selectedRowKeys
  isSingleBackup.value = false
  backupCount.value = len
  backupVisible.value = true
}
//立即备份
const singleBackup = (item: BackupsItem, index: number) => {
  currentIndex.value = index
  formState.tables_name = [item.table_name]
  isSingleBackup.value = true
  backupCount.value = 1
  backupVisible.value = true
}
//关闭弹窗重置表单
const afterCloseFunc = () => {
  formState.backups_name = ''
}
/**
  备份对话框事件
 */
const backupConfirm = () => {
  console.log('formState: ', formState)
  formRef.value.validate().then(() => {
    recycle_create(formState).then(() => {
      backupVisible.value = false
      message.success('创建备份成功')
      if (isSingleBackup.value) {
        state.recycleList[currentIndex.value].status = 1
      } else {
        state.recycleList.forEach((item) => {
          if (statusState.selectedRowKeys.includes(item.table_name)) item.status = 1
        })
      }
      statusState.selectedRowKeys = []
    })
  })
}
const backupCancel = () => {
  backupVisible.value = false
}
onMounted(() => {
  statusState.selectedRowKeys = []
  getBackupList()
})
</script>
<style lang="less" scoped>
@basicColor: #0083ff;
.dotClass {
  width: 7px;
  height: 7px;
  border-radius: 50%;
  display: block;
  margin-left: 10px; //这个用于圆点居中
}
:deep(.ant-form-item-label) {
  width: 80px;
  text-align: right;
}

:deep(.ant-form-item-label > label::after) {
  content: '';
}

.page-albumList {
  padding-top: 6px;
  box-sizing: border-box;

  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not(
          [colspan]
        )::before
    ) {
    width: 0;
  }

  :deep(.ant-table-cell .ant-table-cell-with-append) {
    display: flex;
    align-items: center;
  }

  :deep(.ellipsis-text) {
    max-width: 154px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }

  .basicColor {
    color: @basicColor;
  }
}
</style>
